package com.walming.generator.support.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.walming.generator.copycat.mybatisplus.service.impl.ServiceImpl;
import com.walming.generator.common.cache.SysCacheUtils;
import com.walming.generator.common.constant.Constants;
import com.walming.generator.common.constant.StringConstants;
import com.walming.generator.common.exception.BusinessException;
import com.walming.generator.common.utils.StringUtils;
import com.walming.generator.common.utils.text.Convert;
import com.walming.generator.support.domain.SysConfig;
import com.walming.generator.support.mapper.SysConfigMapper;
import com.walming.generator.support.service.ISysConfigService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Map;

/**
 * 系统配置 业务层处理
 *
 * @author walming
 */
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService {

    /**
     * 项目启动时，初始化参数到缓存
     */
    //@PostConstruct
    public void init() {
        this.list().forEach(config -> SysCacheUtils.put(config.getConfigKey(), config.getConfigValue()));
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Override
    @Cacheable(value = SysCacheUtils.SYS_CONFIG_CACHE, key = "'sys_key:' + #configKey")
    public String selectConfigByKey(String configKey) {
        SysConfig sysConfig = this.getOne(new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getConfigKey, configKey));
        return StringUtils.isNotNull(sysConfig) ? sysConfig.getConfigValue() : StringConstants.EMPTY_STRING;
    }

    /**
     * 新增参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int insertConfig(SysConfig config) {
        config.setIsBuiltIn(Constants.NO);
        int row = this.baseMapper.insert(config);
        if (row > 0) {
            SysCacheUtils.put(config.getConfigKey(), config.getConfigValue());
        }
        return row;
    }

    /**
     * 批量更新参数配置
     *
     * @param configMap 配置信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateConfig(Map<String, Object> configMap) {
        for (Map.Entry<String, Object> entry : configMap.entrySet()) {
            if (entry.getKey() != null && entry.getValue() != null && !SysCacheUtils.get(entry.getKey()).equals(entry.getValue())) {
                int row = this.baseMapper.update(
                        new SysConfig().setConfigValue(entry.getValue().toString()),
                        new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getConfigKey, entry.getKey()));
                if (row > 0) {
                    SysCacheUtils.put(entry.getKey(), entry.getValue());
                }
            }
        }
    }

    /**
     * 修改参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int updateConfig(SysConfig config) {
        int row = this.baseMapper.updateById(config);
        if (row > 0) {
            SysCacheUtils.put(config.getConfigKey(), config.getConfigValue());
        }
        return row;
    }

    /**
     * 批量删除参数配置对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteConfigByIds(String ids) {
        Long[] configIds = Convert.toLongArray(ids);
        for (Long configId : configIds) {
            SysConfig config = this.getById(configId);
            if (config.isBuiltIn()) {
                throw new BusinessException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey()));
            } else {
                SysCacheUtils.remove(config.getConfigKey());
            }
        }
        int count = this.baseMapper.deleteBatchIds(Arrays.asList(Convert.toStrArray(ids)));
        if (count > 0) {
            clearCache();
        }
        return count;
    }

    /**
     * 清空缓存数据
     */
    @Override
    public void clearCache() {
        SysCacheUtils.removeAll();
    }

    /**
     * 校验参数键名是否唯一
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public String checkConfigKeyUnique(SysConfig config) {
        long configId = StringUtils.isNull(config.getConfigId()) ? -1L : config.getConfigId();
        SysConfig info = this.getOne(new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getConfigKey, config.getConfigKey()));
        return (StringUtils.isNotNull(info) && info.getConfigId() != configId) ? Constants.CONFIG_KEY_NOT_UNIQUE : Constants.CONFIG_KEY_UNIQUE;
    }

}
